package com.sskj.hhrt.transaction;

import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.github.tifezh.kchartlib.chart.formatter.TimeFormatter;
import com.hjq.toast.ToastUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.sskj.base.adapter.BaseAdapter;
import com.sskj.base.adapter.ViewHolder;
import com.sskj.base.utils.ClickUtil;
import com.sskj.base.utils.DateUtil;
import com.sskj.base.utils.NumberUtil;
import com.sskj.base.utils.RxUtils;
import com.sskj.base.view.DividerLineItemDecoration;
import com.sskj.hhrt.MVPFragment;
import com.sskj.hhrt.MyApplication;
import com.sskj.hhrt.R;
import com.sskj.hhrt.transaction.data.CoinDetail;
import com.sskj.hhrt.transaction.data.HoldOrderBean;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * @author Hey
 * Create at  2019/03/20
 */
public class HoldPositionFragment extends MVPFragment<HoldPositionPresenter> {
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    private BaseAdapter<HoldOrderBean> baseAdapter;

    private Disposable disposable;
    DecimalFormat format = new DecimalFormat("0.###");

    @Override
    public int getLayoutId() {
        return R.layout.fragment_hode_position;
    }

    @Override
    public HoldPositionPresenter getPresenter() {
        return new HoldPositionPresenter();
    }

    @Override
    public void initView() {
        initRefreshLayout(smartRefreshLayout);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(getActivity())
                .setPaintWidth(20)
                .setFirstDraw(false)
                .setDividerColor(Color.parseColor("#00ffffff"))
        );
        baseAdapter = new BaseAdapter<HoldOrderBean>(R.layout.item_hold_position, null, recyclerView, true) {
            @Override
            public void bind(ViewHolder holder, HoldOrderBean item) {
                holder.setText(R.id.tv_type, item.getOtype() == 1 ? "融资" : "融券")
                        .setTextColor(R.id.tv_type, getResources().getColor(item.getOtype() == 1 ? R.color.text_e83 : R.color.color_03c087))
                        .setText(R.id.tv_name, item.getPname())
                        .setText(R.id.tv_create_time, DateUtil.getDateFormat(Long.valueOf(Long.valueOf(item.getAddtime()) * 1000), DateUtil.PATTERN_J))
                        .setText(R.id.tv_buy_price, item.getBuyprice())
                        .setText(R.id.tv_new_price, item.getNewprice())
                        .setText(R.id.tv_hold_position, item.getBuynum())
                        .setText(R.id.tv_profit_loss, item.getFdyk())
                        .setText(R.id.tv_promise_money, item.getDeposit())
                        .setText(R.id.tv_night_price, item.getDayfee())
                        .setText(R.id.tv_service_charge, item.getSxfee());

                if (item.getOtype() == 1) {
                    holder.setTextColor(R.id.tv_type, color(R.color.red));
                } else {
                    holder.setTextColor(R.id.tv_type, color(R.color.green));
                }

                if (Float.parseFloat(item.getFdyk()) > 0) {
                    holder.setTextColor(R.id.tv_profit_loss, color(R.color.red));
                } else {
                    holder.setTextColor(R.id.tv_profit_loss, color(R.color.green));
                }
                //平仓
                ClickUtil.click(holder.getView(R.id.btn_hold_position), view -> {
                    new AlertDialog.Builder(getContext())
                            .setTitle("提示")
                            .setMessage("确定要平仓吗？")
                            .setPositiveButton("确定", (dialog, which) -> {
                                dialog.dismiss();
                                mPresenter.closeOrder(item.getHold_id());
                            }).setNegativeButton("取消", (dialog, which) -> dialog.dismiss())
                            .show();
                });

//                ClickUtil.click(holder.getView(R.id.btn_hold_setting), view -> {  // 设置止盈止损
//                    mPresenter.getCoinDetail(account, item);
//                });
            }
        };

    }

    @Override
    public void initListener() {
        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {

            }

            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                mPresenter.getHoldList(getAccount(), false);
            }
        });
    }

    @Override
    public void initData() {

    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            if (!TextUtils.isEmpty(MyApplication.getAccount()) && !TextUtils.isEmpty(MyApplication.getToken())) {
                mPresenter.getHoldList(getAccount(), false);
                Observable.interval(10, TimeUnit.SECONDS)
                        .compose(RxUtils.transform())
                        .subscribe(new Observer<Long>() {
                            @Override
                            public void onSubscribe(Disposable d) {
                                disposable = d;
                            }

                            @Override
                            public void onNext(Long aLong) {
                                mPresenter.getHoldList(getAccount(), false);
                            }

                            @Override
                            public void onError(Throwable e) {
                                e.printStackTrace();
                            }

                            @Override
                            public void onComplete() {

                            }
                        });
            }
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (disposable != null) {
            disposable.dispose();
        }
    }

    public void finishRefresh() {
        smartRefreshLayout.finishRefresh();
        smartRefreshLayout.finishLoadMore();
    }

    public static HoldPositionFragment newInstance() {
        HoldPositionFragment fragment = new HoldPositionFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    public void setData(List<HoldOrderBean> data) {
        baseAdapter.setNewData(data);
        smartRefreshLayout.setNoMoreData(true);
    }

    public void closeOrderSuccess() {
        ToastUtils.show("平仓成功");
        mPresenter.getHoldList(getAccount(), true);
        if (getParentFragment() != null) {
            TransactionHomeFragment fragment = (TransactionHomeFragment) getParentFragment();
            fragment.getPresenter().getAccountDetail(getAccount(), true);
        }
    }

    public void setCoinDetail(List<CoinDetail> data, HoldOrderBean bean) {
        if (data != null) {
            CoinDetail coinDetail = data.get(0);
            BottomSheetDialog dialog = new BottomSheetDialog(getContext());
            View dialogView = LayoutInflater.from(getContext()).inflate(R.layout.set_profit, null);
            dialog.setContentView(dialogView);
            dialog.show();
            TextView cancelText = dialogView.findViewById(R.id.cancel);
            TextView nameText = dialogView.findViewById(R.id.name);
            TextView typeText = dialogView.findViewById(R.id.type);
            EditText winEdit = dialogView.findViewById(R.id.edt_win);
            EditText lossEdit = dialogView.findViewById(R.id.edt_loss);
            Button confirmButton = dialogView.findViewById(R.id.btn_confirm);
            cancelText.setOnClickListener(v -> dialog.dismiss());
            setText(nameText, coinDetail.getName());

            setText(typeText, bean.getCountStatus() == 1 ? "做多" : "做空");
            if (bean.getCountStatus() == 1) {
                typeText.setTextColor(color(R.color.red));
            } else {
                typeText.setTextColor(color(R.color.green));
            }
            setText(winEdit, bean.getStopProfitPrice() + "");
            setText(lossEdit, bean.getStopLossPrice() + "");

            double price = Double.parseDouble(coinDetail.getPrice());
            double minChange = Double.parseDouble(coinDetail.getJggd());
            double minLoss = coinDetail.getStopLoss();
            ClickUtil.click(confirmButton, view -> {
                if (!isEmpty(winEdit)) {
                    double win = Double.parseDouble(getText(winEdit));
                    if (win < 0) {
                        ToastUtils.show("止损价格不能为负数");
                    }
                    if (win != 0) {
                        if (bean.getCountStatus() == 1) {
                            double range = price + minLoss * minChange;
                            range = NumberUtil.formatDouble(range, 3);
                            if (win < range) {
                                ToastUtils.show("止盈价格必须大于" + range);
                                return;
                            }
                        } else {
                            double range = price - minLoss * minChange;
                            range = NumberUtil.formatDouble(range, 3);
                            if (win > range) {
                                ToastUtils.show("止盈价格必须小于" + range);
                                return;
                            }
                        }
                    }


                }

                if (!isEmpty(lossEdit)) {
                    double win = Double.parseDouble(getText(lossEdit));
                    if (win < 0) {
                        ToastUtils.show("止损价格不能为负数");
                    }
                    if (win != 0) {
                        if (bean.getCountStatus() == 1) {
                            double range = price - minLoss * minChange;
                            range = NumberUtil.formatDouble(range, 3);
                            if (win > range) {
                                ToastUtils.show("止损价格必须小于" + range);
                                return;
                            }
                        } else {
                            double range = price + minLoss * minChange;
                            range = NumberUtil.formatDouble(range, 3);
                            if (win < range) {
                                ToastUtils.show("止损价格必须大于" + range);
                                return;
                            }

                        }
                    }

                }
                dialog.dismiss();
                mPresenter.setProfit(account, bean.getId() + "", isEmpty(winEdit) ? "0" : getText(winEdit), isEmpty(lossEdit) ? "0" : getText(lossEdit));
            });

        }

    }

    public void setProfitSuccess() {
        ToastUtils.show("修改成功");
        mPresenter.getHoldList(account, true);
    }
}
